/**
 *
 */
package de.guidoludwig.af;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.ListResourceBundle;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Logger;

import javax.swing.Icon;
import javax.swing.ImageIcon;

import de.guidoludwig.jtm.util.StringUtil;

/**
 * @author guido
 *
 */
public class AFProperties extends ListResourceBundle {

	private final static String resourcPath = "resources" + File.separator;
	private static final AFProperties DEFAULT = new AFProperties(AFProperties.class);

	private final Properties properties;
	private final Class clazz;

	public AFProperties(@SuppressWarnings("rawtypes") Class clazz) {
		if (clazz == null) {
			throw new NullPointerException("Class must not be null");
		}
		this.clazz = clazz;
		String path = resourcPath + clazz.getSimpleName() + ".properties";
		URL url = clazz.getResource(path);
		if (url == null) {
			throw new NullPointerException("Can't load properties for " + path);
		}
		properties = new Properties();
		try {
			properties.load(new FileReader(url.getPath()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param key
	 * @return an Icon from the value represented by the key If the key could
	 *         not be found or the icon does not exist, null is returned
	 */
	public Icon getIcon(String key) {
		String value = getString(key);
		if (StringUtil.isBlank(value)) {
			return null;
		}
		String path = resourcPath + value;
		URL url = clazz.getResource(path);
        if (url == null) {
        	Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).warning("icon " + value + " not found"); //$NON-NLS-1$ //$NON-NLS-2$
            return null;
        }
        return new ImageIcon(url);
	}


	@Override
	protected Object[][] getContents() {
		Set<Entry<Object, Object>> entries = properties.entrySet();
		if (entries.size() == 0) {
			return null;
		}
		Object[][] result = new Object[entries.size()][2];
		int i = 0;
		for (Entry<Object, Object> entry : properties.entrySet()) {
			result[i] = createEntry(entry);
			i++;
		}
		return result;
	}

	private Object[] createEntry(Entry<Object, Object> entry) {
		String[] result = new String[2];
		result[0] = (String) entry.getKey();
		result[1] = (String) entry.getValue();
		if (result[1] != null && result[1].startsWith("${")) {
			String dk = result[1].replace('$', ' ').replace('{', ' ').replace('}', ' ').trim();
			result[1] =  DEFAULT.getString(dk);
		}
		return result;
	}

	public static void main(String[] args) throws ClassNotFoundException,
			IOException {
		new AFProperties(AFProperties.class);
	}

}
